﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KPIS.GERP.Models.SYS;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GIMS.Class;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class SearchController : Controller
    {
        public ActionResult SearchKeywords(string keywords, string keywords2, string SeachOption, FormCollection formCollection, string SearchByEmployeeNameExactName = "off")
        {
            keywords = keywords + " " + keywords2;
            SearchCriteriaVM model = new SearchCriteriaVM();
            model.RequestByEmpId = GimsMembership.CurrentEmpId;
            model.SearchTitleOnly = true;
            model.SeachOption = !string.IsNullOrWhiteSpace(SeachOption) ? SeachOption : KPIS.GERP.Models.SYS.SeacrhOptionEnum.ทั้งหมด;
            model.SortResultByType = KPIS.GERP.Models.SYS.SortResultByTypeEnum.วันที่;
            model.SortResultOrdering = KPIS.GERP.Models.SYS.SortResultOrderingEnum.มากไปน้อย;
            model.SearchKeyword = keywords;
            string errorMessage;
            model.SearchByEmployeeNameExactName = Models.Class.CompareUtility.IsObjectToStringEqual(SearchByEmployeeNameExactName, "on");
            var modelResult = new SysSearchService.SysSearchServiceClient().SelectSearch(model, out errorMessage);
            Session["LastestSearchResult"] = modelResult;
            TempData["ErrorMessage"] = errorMessage;
            return RedirectToAction("SearchResult", new
                {
                    SearchId = modelResult != null ? (int?) modelResult.SearchId : null,
                    keywords = model.SearchKeyword
                });
        }

        public ActionResult SearchResult(int? searchId = null)
        {
            ViewBag.ErrorMessage = TempData["ErrorMessage"];
            SearchResult modelResult;
            if(Session["LastestSearchResult"] as SearchResult != null) modelResult = Session["LastestSearchResult"] as SearchResult;
            else if(searchId.HasValue) modelResult = new SysSearchService.SysSearchServiceClient().SelectSearchResult(searchId.Value);
            else modelResult = null;

            if (modelResult == null && searchId != null) return RedirectToAction("SearchResult");
            
            Session["LastestSearchResult"] = modelResult;
            ViewBag.SearchResult  = modelResult;

            return View();

        }
    }
}